import { fileURLToPath, URL } from 'node:url'
import path from 'path'
import { defineConfig,loadEnv } from 'vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
const port = process.env.port || process.env.npm_config_port || 8088;
export default (mode: string) => {
  const root = process.cwd()
  const env = loadEnv(mode, root)
  const { VITE_VERSION, VITE_PORT, VITE_BASE_URL, VITE_API_URL } = env
  console.log(`🚀 API_URL = ${VITE_API_URL}`)
  console.log(`🚀 VERSION = ${VITE_VERSION}`)
  console.log(`🚀 VITE_PORT = ${VITE_PORT}`)
  return defineConfig({
    define: {
      __APP_VERSION__: JSON.stringify(VITE_VERSION)
    },
    base: VITE_BASE_URL,
    server: {
      port: parseInt(VITE_PORT),
      proxy: {
        '/api': {
          target: VITE_API_URL,
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/api/, '')
        }
      },
      host: true
    },
        // 路径别名
        resolve: {
          alias: {
            '@': resolvePath('src'),
            '@views': resolvePath('src/views'),
            '@comps': resolvePath('src/components'),
            '@imgs': resolvePath('src/assets/img'),
            '@icons': resolvePath('src/assets/icons'),
            '@utils': resolvePath('src/utils'),
            '@stores': resolvePath('src/store'),
            '@plugins': resolvePath('src/plugins'),
            '@styles': resolvePath('src/assets/styles')
          }
        },
        build: {
          target: 'es2015',
          outDir: 'dist',
          chunkSizeWarningLimit: 2000,
          minify: 'terser',
          terserOptions: {
            compress: {
              drop_console: true, // 生产环境去除 console
              drop_debugger: true // 生产环境去除 debugger
            }
          },
          rollupOptions: {
            output: {
              manualChunks: {
                vendor: ['vue', 'vue-router', 'pinia', 'element-plus']
              }
            }
          }
        },
    plugins: [
      vue(),
      // 自动导入 components 下面的组件，无需 import 引入
      Components({
        deep: true,
        extensions: ['vue'],
        dirs: ['src/components'], // 自动导入的组件目录
        resolvers: [ElementPlusResolver()],
        dts: 'src/types/components.d.ts' // 指定类型声明文件的路径
      }),
      AutoImport({
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia'],
        resolvers: [ElementPlusResolver()],
        dts: 'src/types/auto-imports.d.ts',
        eslintrc: {
          // 这里先设置成true然后pnpm dev 运行之后会生成 .auto-import.json 文件之后，在改为false
          enabled: true,
          filepath: './.auto-import.json',
          globalsPropValue: true
        }
      }),
      vueDevTools(),
    ]
  })
}

function resolvePath(paths: string) {
  return path.resolve(__dirname, paths)
}

